package controllers

import (
	"CRMSystem/models"
	"encoding/json"
	"fmt"
)

type CustomerChangeController struct {
	MainController
}

// GetContact 获得联系人信息
func (c *CustomerChangeController) GetContact() {
	c.IfHasSession()
	contact, b := GetSessionContact(c.GetSession("Contact"))
	if b {
		contacts, err := models.SelectByContactId(contact.ContactId)
		if err != nil {
			c.Data["json"] = Status{ErrCode: GET_ERR, Msg: "GetContact ERR"}
			c.ServeJSON()
			c.StopRun()
		}
		c.Data["json"] = Status{Date: contacts, ErrCode: GET_OK, Msg: "GetContact OK"}
		c.ServeJSON()
		c.StopRun()
	} else {
		c.Data["json"] = Status{ErrCode: GET_ERR, Msg: "GetContact Session ERR"}
		c.ServeJSON()
		c.StopRun()
	}
}

func (c *CustomerChangeController) Submit() {
	c.IfHasSession()
	form := new(models.FormData)
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &form); err == nil {
		contacts, _ := models.SelectByPhoneNumber(form.PhoneNumber)
		contact, _ := GetSessionContact(c.GetSession("Contact"))
		if contact.ContactId != contacts.ContactId {
			c.Data["json"] = Status{Date: 0, ErrCode: POST_ERR, Msg: "电话号码不是你本人的"}
			c.ServeJSON()
			c.StopRun()
		}
		if contacts.ContactId != 0 {
			username := GetSessionString(c.GetSession("UserName"))
			fmt.Println(username)
			_ = models.ChangePassword(username, form.Password)
			c.Data["json"] = Status{Date: 1, ErrCode: POST_OK, Msg: "Submit OK"}
			c.ServeJSON()
			c.StopRun()
		} else {
			c.Data["json"] = Status{Date: 0, ErrCode: POST_ERR, Msg: "Submit ERR"}
			c.ServeJSON()
			c.StopRun()
		}
	} else {
		c.Data["json"] = Status{Date: 0, ErrCode: POST_ERR, Msg: "Submit ERR"}
		c.ServeJSON()
		c.StopRun()
	}
}

func (c *CustomerChangeController) UnLogin() {
	c.DestroySession()
	c.Redirect("/page/login", 302)
}
